# -*- coding:utf-8 -*-
import logging
import smtplib
from email.header import Header
from email.mime.text import MIMEText
from email.utils import formataddr

logging.basicConfig(level=logging.DEBUG, format="%(asctime)s %(name)s %(levelname)s lineno:%(lineno)d %(message)s")
logger = logging.getLogger('mail.sender')

class MailSender(object):

    def __init__(self):

        self.retry_count = 0

        self.smtp_server = 'smtp.exmail.qq.com'
        self.smtp_sslport = 465
        self.sender_name = 'HLCTECH'
        self.sender = 'hotel@hlctech.com'
        self.sender_password = 'Hote@Hlc123'

        # self.receivers = ["yangxuefeng@jsj.com.cn"]
        self.receivers = []

    # send mail
    def _send_mail(self, receivers, subject, text):

        msg = MIMEText(text, 'html', 'utf-8')
        msg['Subject'] = Header(subject, 'utf-8')

        sender_name = str(Header(self.sender_name, 'utf-8'))
        msg['From'] = formataddr((sender_name, self.sender))

        logger.debug('connect [{}] ...'.format(self.smtp_server))
        smtp = smtplib.SMTP_SSL(self.smtp_server, self.smtp_sslport)
        try:
            smtp.ehlo()
            logger.debug('login [{}] ...'.format(self.sender))
            smtp.login(self.sender, self.sender_password)

            logger.debug('start send mail ... ')
            smtp.sendmail(self.sender, receivers, msg.as_string())
            logger.debug('send mail finished ! ')
        except Exception, e:
            logger.error(e)
            logger.debug('send mail error! {}, retry:{}'.format(e.message, self.retry_count))
            self.retry_count = self.retry_count + 1

            if self.retry_count <= 5:
                self._send_mail(receivers, subject, text)

        finally:
            smtp.quit()
            self.retry_count = 0